/**
 * base64转File
 */
function URL2Blob(base64, filename, resolvePath = true) {
	let arr = base64.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	let file = new File([u8arr], `${filename}.${mime.split('/')[1]}`, {
		type: mime
	});
	let urlBlob = file;
	if (resolvePath) {
		urlBlob = (window.URL || window.webkitURL).createObjectURL(file)
	}
	return urlBlob;
}
/**
 * 网络图片，或者本地图片转base64
 * @param {path}  	网络路径、本地路径 string
 * @param {format}  自定义base64的类型，默认值 'png'
 * @param {compress}  压缩图片百分比，默认不压缩 0-1之间，值越大越清晰
 */
function appendFile(path, format = 'png', compress = 1) {
	return new Promise((resolve, reject) => {
		let img = new Image();
		img.setAttribute('crossOrigin', 'Anonymous');
		img.src = path;
		img.onload = function() {
			let w = this.width,
				h = this.height;
			let canvas = document.createElement('canvas');
			let ctx = canvas.getContext('2d');
			canvas.setAttribute('width', w);
			canvas.setAttribute('height', h);
			ctx.drawImage(this, 0, 0, w, h);
			let base64 = canvas.toDataURL('image/jpeg', compress);
			base64 = base64.replace(/^data\:image.{0,}base64,/i, `data:image/${format};base64,`);
			resolve(base64);
		}
		img.onerror = reject
	})
}


class Wave {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.t = Date.now()
    }
    render(ctx, now, speed) {
        let age = now - this.t
        let r = age * speed
        ctx.shadowColor = '#000';
        ctx.shadowBlur = 8;
        ctx.shadowOffsetX = 4;
        ctx.shadowOffsetY = 4;
        ctx.beginPath();
        ctx.strokeStyle = 'rgba(30,30,30,0.6)'
        ctx.lineWidth = 8
        ctx.arc(this.x, this.y, r, 0, 2 * Math.PI)
        ctx.stroke()
    }
}


module.exports = {
	URL2Blob,
	appendFile,
	Wave
}
